package logger

import (
	"io/ioutil"
	"log"
	"os"
	"time"
)

const logDir = "logs"

// LogError 当存在错误时记录日志
func LogError(err error) {
	if err != nil {
		putFileLog("[INFO]", err)
	}
}
func Info(message ...interface{}) {
	putFileLog("[INFO]", message)
}

func Error(message ...interface{}) {
	putFileLog("[ERROR]", message)
}
func Dbug(message ...interface{}) {
	putFileLog("[DNUG]", message)
}

// 写入日志
func putFileLog(level string, message ...interface{}) {
	t := time.Now().Format(time.DateOnly)
	filepath := logDir + "/" + t + ".log"
	file, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDONLY|os.O_APPEND, os.ModePerm)
	if err != nil {
		log.Println("Open logs file failed!")
		return
	}

	defer file.Close()
	log.SetOutput(file)

	log.Println(level, message)
}

// 删除过去七天的日志
func DeleteOldLogs() {
	files, err := ioutil.ReadDir(logDir)
	if err != nil {
		log.Println("Failed to list directory:", err)
		return
	}

	sevenDaysAgo := time.Now().AddDate(0, 0, -7)
	for _, file := range files {
		filePath := logDir + "/" + file.Name()
		fileInfo, err := os.Stat(filePath)
		if err != nil {
			log.Println("Failed to get file info:", err)
			continue
		}

		if fileInfo.ModTime().Before(sevenDaysAgo) {

			if err := os.Remove(filePath); err != nil {

				log.Println("Failed to delete file:", err)

			} else {

				log.Println("Deleted old log file:", file.Name())

			}
		}
	}
}
